package cn.com.project.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class GenerateIdUtil {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");

    private static Random random = new Random();

    /* 不能在多线程环境下调用 */
    public String generateId(String orderPrefix) {
        String prefix = orderPrefix + LocalDateTime.now().format(dateTimeFormatter);
        RedisAtomicLong counter = new RedisAtomicLong(prefix, redisTemplate.getConnectionFactory());
        counter.expire(5, TimeUnit.SECONDS); // 1、设置过期时间 2、避免不同机器时钟差异造成id重复
        return prefix + String.format("%04d", counter.incrementAndGet()) + (random.nextInt(90) + 10);
    }

}
